package org.lc.gateway.filter;

import cn.hutool.core.util.ObjUtil;
import lombok.extern.slf4j.Slf4j;
import org.lc.gateway.context.GatewayContext;
import org.lc.gateway.enums.FilterOrderEnum;
import org.lc.gateway.util.SchemeUtil;
import org.reactivestreams.Publisher;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.cloud.gateway.filter.factory.rewrite.CachedBodyOutputMessage;
import org.springframework.cloud.gateway.support.BodyInserterContext;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.http.*;
import org.springframework.http.server.reactive.ServerHttpResponseDecorator;
import org.springframework.web.reactive.function.BodyInserter;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.client.ClientResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.Objects;

/**
 * 读取并缓存响应数据
 * Quoted from @see
 */
@Slf4j
@SuppressWarnings("all")
public class GatewayResponseContextFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        GatewayContext gatewayContext = exchange.getAttribute(GatewayContext.CACHE_GATEWAY_CONTEXT);
        if (ObjUtil.isNotNull(gatewayContext) && !gatewayContext.getReadResponseData()) {
            return chain.filter(exchange);
        }
        ServerHttpResponseDecorator responseDecorator = new ServerHttpResponseDecorator(exchange.getResponse()) {

            private Mono<Void> callbackMono(BodyInserter<Flux<DataBuffer>, ReactiveHttpOutputMessage> bodyInserter, CachedBodyOutputMessage outputMessage, Flux<DataBuffer> cachedFlux) {
                return Mono.defer(() -> bodyInserter.insert(outputMessage, new BodyInserterContext())
                        .then(Mono.defer(() -> {
                            Flux<DataBuffer> messageBody = cachedFlux;
                            HttpHeaders headers = getDelegate().getHeaders();
                            if (!headers.containsKey(HttpHeaders.TRANSFER_ENCODING)) {
                                messageBody = messageBody.doOnNext(data -> headers.setContentLength(data.readableByteCount()));
                            }
                            return getDelegate().writeWith(messageBody);
                        })));
            }


            private Flux<DataBuffer> getBody(Publisher<? extends DataBuffer> body) {
                Flux<DataBuffer> flux = null;
                if (body instanceof Flux) {
                    flux = (Flux<DataBuffer>) body;
                } else {
                    flux = ((Mono) body).flux();
                }
                return flux;
            }

            @Override
            public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
                return DataBufferUtils.join(Flux.from(body))
                        .flatMap(dataBuffer -> {

                            var cachedFlux = SchemeUtil.getCacheFlux(dataBuffer, exchange, true);
                            var bodyInserter = BodyInserters.fromDataBuffers(cachedFlux);
                            var headers = exchange.getResponse().getHeaders();
                            var outputMessage = new CachedBodyOutputMessage(exchange, headers);
                            var clientResponse = ClientResponse
                                    .create(Objects.requireNonNull(exchange.getResponse().getStatusCode()))
                                    .headers(h -> h.putAll(headers))
                                    .body(getBody(cachedFlux)).build();

                            return clientResponse.bodyToMono(Object.class)
                                    .doOnNext(originalBody -> {
                                        gatewayContext.setResponseBody(originalBody);
                                    })
                                    .then(callbackMono(bodyInserter, outputMessage, cachedFlux));
                        });

            }

            @Override
            public Mono<Void> writeAndFlushWith(Publisher<? extends Publisher<? extends DataBuffer>> body) {
                return writeWith(Flux.from(body)
                        .flatMapSequential(p -> p));
            }
        };
        return chain.filter(exchange.mutate().response(responseDecorator).build());
    }

    @Override
    public int getOrder() {
        return FilterOrderEnum.RESPONSE_DATA_FILTER.getOrder();
    }
}
